package com.wtj.security.config;

import com.wtj.security.filter.JwtAuthenticationTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * SecurityConfig
 */
//1.开启全局权限控制
@EnableGlobalAuthentication
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    /**
     * 密码加密
     * 1.将数据库中明文存储的密码替换为加密后的密码
     * 2.通过测试类，生成一个加密后的密码
     * 3.将加密后的密码存储到数据库中
     * USE isecurity;
     * UPDATE sys_user SET password = '$2a$10$8VfwUGRIUmWUeUmwoIYedOVys8bSj/Kg/pfRsWCNNwbUmYNlfaFb2' WHERE id = 1
     * UPDATE sys_user SET password = '$2a$10$8VfwUGRIUmWUeUmwoIYedOVys8bSj/Kg/pfRsWCNNwbUmYNlfaFb2' WHERE id = 2
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 重写configure方法，配置HttpSecurity
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 禁用CSRF保护
                .csrf().disable()
                // 设置会话管理策略为无状态
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 配置授权请求
                .authorizeRequests()
                // 允许匿名访问/user/login
                .antMatchers("/user/login").anonymous()
                // 其他请求都需要认证
                .anyRequest().authenticated();
        // 当创建好过滤器后，添加JWT认证过滤器到security 过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    }

    /**
     * 重写authenticationManagerBean方法，返回AuthenticationManager对象
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 重写configure方法，配置WebSecurity
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

}
